﻿// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Echo.Server
{
    using System;
    using System.Text;
    using DotNetty.Buffers;
    using DotNetty.Transport.Channels;

    public class EchoServerHandler : ChannelHandlerAdapter
    {
        /**
         * Channel的声明周期
         * 1.ChannelRegistered 先注册
         * 2.ChannelActive 再被激活
         * 3.ChannelRead 客户端与服务端建立连接之后的会话 (数据交互)
         * 4.ChannelReadComplete 读取客户端发送的消息完成之后
         * 5.ChannelInactive 使当前频道处于未激活状态
         * 6.ChannelUnregistered 取消注册
         * ExceptionCaught 如果在会话过程当中出现dotnetty框架内部异常都会通过ExceptionCaught方法返回给开发者
         */

        /// <summary>
        /// 半连接(比如TCP半连接)状态
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelRegistered(IChannelHandlerContext context)
        {
            base.ChannelRegistered(context);
        }

        /// <summary>
        /// 全连接,与客户端建立链接成功了之后
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelActive(IChannelHandlerContext context)
        {
            base.ChannelActive(context);
        }

        /// <summary>
        /// 客户端与服务端建立连接之后的会话(数据交互),相当于原生System.Net.Sockets.Socket的Receive方法(接收数据)
        /// </summary>
        /// <param name="context"></param>
        /// <param name="message"></param>
        public override void ChannelRead(IChannelHandlerContext context, object message)
        {
            var buffer = message as IByteBuffer;
            if (buffer != null)
            {
                Console.WriteLine("Received from client: " + buffer.ToString(Encoding.UTF8));
            }
            context.WriteAsync(message);
        }

        /// <summary>
        /// 读取客户端发送的消息完成之后,context.Flush():把接收到的数据,存放到接收数据的缓冲池
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelReadComplete(IChannelHandlerContext context) => context.Flush();

        /// <summary>
        /// 异常捕获
        /// </summary>
        /// <param name="context"></param>
        /// <param name="exception"></param>
        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            Console.WriteLine("Exception: " + exception);
            context.CloseAsync();
        }

        /// <summary>
        /// 使当前频道处于未激活状态
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelInactive(IChannelHandlerContext context)
        {
            base.ChannelInactive(context);
        }

        /// <summary>
        /// 取消注册
        /// </summary>
        /// <param name="context"></param>
        public override void ChannelUnregistered(IChannelHandlerContext context)
        {
            base.ChannelUnregistered(context);
        }
    }
}